package com.ffggffgfv.backend.service.impl;

import com.ffggffgfv.backend.dto.CartDisplayDTO;
import com.ffggffgfv.backend.dto.OrderCreateDTO;
import com.ffggffgfv.backend.dto.OrderDetailDTO;
import com.ffggffgfv.backend.dto.OrderQueryDTO;
import com.ffggffgfv.backend.dto.PageResult;
import com.ffggffgfv.backend.dto.PaymentDTO;
import com.ffggffgfv.backend.entity.Cart;
import com.ffggffgfv.backend.entity.Order;
import com.ffggffgfv.backend.entity.OrderItem;
import com.ffggffgfv.backend.entity.Product;
import com.ffggffgfv.backend.entity.ShippingAddress;
import com.ffggffgfv.backend.entity.Shipping;
import com.ffggffgfv.backend.mapper.CartMapper;
import com.ffggffgfv.backend.mapper.OrderItemMapper;
import com.ffggffgfv.backend.mapper.OrderMapper;
import com.ffggffgfv.backend.mapper.ProductMapper;
import com.ffggffgfv.backend.mapper.ShippingAddressMapper;
import com.ffggffgfv.backend.mapper.ShippingMapper;
import com.ffggffgfv.backend.service.CartService;
import com.ffggffgfv.backend.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单服务实现类
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ShippingMapper shippingMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private ShippingAddressMapper shippingAddressMapper;

    /**
     * 创建订单
     *
     * @param userId 用户ID
     * @param orderCreateDTO 订单创建信息
     * @return 订单号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createOrder(Long userId, OrderCreateDTO orderCreateDTO) {
        // 1. 获取购物车中选中的商品
        List<CartDisplayDTO> selectedItems;
        if (orderCreateDTO.getSelectedCartItems() != null && !orderCreateDTO.getSelectedCartItems().isEmpty()) {
            // 如果指定了购物车项ID列表，则只获取这些项
            List<Cart> cartItems = new ArrayList<>();
            for (Long cartId : orderCreateDTO.getSelectedCartItems()) {
                Cart cart = cartMapper.selectById(cartId);
                if (cart != null && cart.getUserId().equals(userId)) {
                    cartItems.add(cart);
                }
            }

            // 转换为CartDisplayDTO
            selectedItems = new ArrayList<>();
            for (Cart cart : cartItems) {
                Product product = productMapper.selectById(cart.getProductId());
                if (product == null || product.getStatus() == 0) {
                    throw new RuntimeException("商品不存在或已下架，商品ID: " + cart.getProductId());
                }

                CartDisplayDTO dto = new CartDisplayDTO();
                dto.setId(cart.getId());
                dto.setProductId(product.getId());
                dto.setProductName(product.getName());
                dto.setProductImage(product.getMainImageUrl());
                dto.setPrice(product.getPrice());
                dto.setQuantity(cart.getQuantity());
                dto.setSelected(true);
                // 计算小计金额
                BigDecimal totalPrice = product.getPrice().multiply(new BigDecimal(cart.getQuantity()));
                dto.setTotalPrice(totalPrice);

                selectedItems.add(dto);
            }
        } else {
            // 获取所有选中的购物车项
            selectedItems = cartService.getCartList(userId).stream()
                    .filter(CartDisplayDTO::getSelected)
                    .collect(Collectors.toList());
        }

        if (selectedItems.isEmpty()) {
            throw new RuntimeException("没有选中的商品");
        }

        // 2. 计算总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (CartDisplayDTO item : selectedItems) {
            totalAmount = totalAmount.add(item.getTotalPrice());
        }

        // 3. 生成订单号
        String orderNo = generateOrderNo();        // 4. 创建订单
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setTotalAmount(totalAmount);
        order.setStatus(0); // 待支付
        // 立即购买模式下，shippingId可以为null
        if (orderCreateDTO.getBuyNow() == null || !orderCreateDTO.getBuyNow()) {
            order.setShippingId(orderCreateDTO.getShippingId());
        }
        order.setRemark(orderCreateDTO.getRemark());

        // 5. 保存订单
        orderMapper.insert(order);
        Long orderId = order.getId();

        // 6. 创建订单项
        List<OrderItem> orderItems = new ArrayList<>();
        for (CartDisplayDTO item : selectedItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(orderId);
            orderItem.setProductId(item.getProductId());
            orderItem.setProductName(item.getProductName());
            orderItem.setProductImage(item.getProductImage());
            orderItem.setQuantity(item.getQuantity());
            orderItem.setUnitPrice(item.getPrice());
            orderItem.setTotalPrice(item.getTotalPrice());

            // 尝试获取商品所在的货架ID
            Product product = productMapper.selectById(item.getProductId());
            if (product != null) {
                orderItem.setShelfId(product.getMerchantId()); // 临时使用商家ID代替货架ID
            }

            orderItems.add(orderItem);
        }

        // 7. 保存订单项
        if (!orderItems.isEmpty()) {
            orderItemMapper.batchInsert(orderItems);
        }        // 8. 创建物流信息
        if (orderCreateDTO.getBuyNow() != null && orderCreateDTO.getBuyNow()) {
            // 立即购买模式：创建默认物流信息，无需收货地址
            Shipping shipping = new Shipping();
            shipping.setOrderId(orderId);
            shipping.setReceiverName("待确认");
            shipping.setReceiverPhone("待确认");
            shipping.setReceiverAddress("立即购买，收货地址待确认");
            shipping.setStatus(0); // 待发货

            shippingMapper.insert(shipping);
        } else {
            // 普通订单模式：需要验证收货地址
            ShippingAddress address = shippingAddressMapper.selectById(orderCreateDTO.getShippingId());
            if (address != null && address.getUserId().equals(userId)) {
                Shipping shipping = new Shipping();
                shipping.setOrderId(orderId);
                shipping.setReceiverName(address.getReceiverName());
                shipping.setReceiverPhone(address.getReceiverPhone());
                shipping.setReceiverAddress(address.getFullAddress());
                shipping.setStatus(0); // 待发货

                shippingMapper.insert(shipping);
            } else {
                throw new RuntimeException("收货地址不存在或不属于当前用户");
            }
        }        // 9. 从购物车中删除已下单的商品（立即购买模式下不删除）
        if (orderCreateDTO.getBuyNow() == null || !orderCreateDTO.getBuyNow()) {
            for (CartDisplayDTO item : selectedItems) {
                cartMapper.deleteById(item.getId());
            }
        }

        return orderNo;
    }

    /**
     * 获取订单详情
     *
     * @param userId 用户ID
     * @param orderNo 订单号
     * @return 订单详情
     */
    @Override
    public OrderDetailDTO getOrderDetail(Long userId, String orderNo) {
        // 1. 查询订单
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null || !order.getUserId().equals(userId)) {
            return null;
        }

        // 2. 查询订单项
        List<OrderItem> orderItems = orderItemMapper.selectByOrderId(order.getId());

        // 3. 查询物流信息
        Shipping shipping = shippingMapper.selectByOrderId(order.getId());

        // 4. 组装结果
        OrderDetailDTO detailDTO = new OrderDetailDTO();
        detailDTO.setOrder(order);
        detailDTO.setOrderItems(orderItems);
        detailDTO.setShipping(shipping);

        return detailDTO;
    }

    /**
     * 获取用户的订单列表
     *
     * @param userId 用户ID
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @return 分页订单列表
     */
    @Override
    public PageResult<Order> getUserOrders(Long userId, int pageNum, int pageSize) {
        OrderQueryDTO queryDTO = new OrderQueryDTO();
        queryDTO.setUserId(userId);
        queryDTO.setPageNum(pageNum);
        queryDTO.setPageSize(pageSize);

        return getOrdersByCondition(queryDTO);
    }

    /**
     * 条件查询订单
     *
     * @param queryDTO 查询条件
     * @return 分页订单列表
     */
    @Override
    public PageResult<Order> getOrdersByCondition(OrderQueryDTO queryDTO) {
        // 计算偏移量
        int offset = (queryDTO.getPageNum() - 1) * queryDTO.getPageSize();

        // 查询总数
        long total = orderMapper.countByCondition(queryDTO);

        // 查询当前页数据
        List<Order> orders = orderMapper.selectByCondition(queryDTO, offset, queryDTO.getPageSize());

        // 返回分页结果
        return new PageResult<>(orders, total, queryDTO.getPageNum(), queryDTO.getPageSize());
    }

    /**
     * 取消订单
     *
     * @param userId 用户ID
     * @param orderNo 订单号
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Long userId, String orderNo) {
        // 1. 查询订单
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }

        // 2. 检查订单状态，只有待支付的订单可以取消
        if (order.getStatus() != 0) {
            return false;
        }

        // 3. 更新订单状态为已取消
        int result = orderMapper.updateStatus(orderNo, 0, 4);

        return result > 0;
    }

    /**
     * 支付订单
     *
     * @param userId 用户ID
     * @param paymentDTO 支付信息
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(Long userId, PaymentDTO paymentDTO) {
        // 1. 查询订单
        Order order = orderMapper.selectByOrderNo(paymentDTO.getOrderNo());
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }

        // 2. 检查订单状态，只有待支付的订单可以支付
        if (order.getStatus() != 0) {
            return false;
        }

        // 3. 更新订单状态和支付信息
        order.setStatus(1); // 已支付
        order.setPaymentType(paymentDTO.getPaymentType());
        order.setPaymentTime(new Date());

        int result = orderMapper.update(order);

        return result > 0;
    }

    /**
     * 确认收货
     *
     * @param userId 用户ID
     * @param orderNo 订单号
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmReceipt(Long userId, String orderNo) {
        // 1. 查询订单
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null || !order.getUserId().equals(userId)) {
            return false;
        }

        // 2. 检查订单状态，只有已发货的订单可以确认收货
        if (order.getStatus() != 2) {
            return false;
        }

        // 3. 更新订单状态为已完成
        int orderResult = orderMapper.updateStatus(orderNo, 2, 3);

        // 4. 更新物流状态为已签收
        Shipping shipping = shippingMapper.selectByOrderId(order.getId());
        if (shipping != null) {
            shippingMapper.updateStatus(shipping.getId(), 1, 2);
        }

        return orderResult > 0;
    }

    /**
     * 关闭超时未支付的订单
     *
     * @param timeoutMinutes 超时时间（分钟）
     * @return 处理的订单数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int closeTimeoutOrders(int timeoutMinutes) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, -timeoutMinutes);
        Date timeoutTime = calendar.getTime();

        return orderMapper.closeTimeoutOrders(timeoutTime);
    }

    /**
     * 处理订单发货
     *
     * @param orderNo 订单号
     * @param trackingNo 物流单号
     * @param shippingCompany 物流公司
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean shipOrder(String orderNo, String trackingNo, String shippingCompany) {
        // 1. 查询订单
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null) {
            return false;
        }

        // 2. 检查订单状态，只有已支付的订单可以发货
        if (order.getStatus() != 1) {
            return false;
        }

        // 3. 更新订单状态为已发货
        int orderResult = orderMapper.updateStatus(orderNo, 1, 2);

        // 4. 更新物流信息
        if (orderResult > 0) {
            Shipping shipping = shippingMapper.selectByOrderId(order.getId());
            if (shipping != null) {
                int shippingResult = shippingMapper.updateTracking(shipping.getId(), trackingNo, shippingCompany);
                return shippingResult > 0;
            }
        }

        return false;
    }    @Override
    public Order getOrderByOrderNo(String orderNo) {
        return orderMapper.selectByOrderNo(orderNo);
    }

    @Override
    public boolean updateOrderStatusByOrderNo(String orderNo, Integer status, String tradeNo) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null) {
            return false;
        }
        
        // 如果有支付宝交易号，可以在这里记录到数据库或日志中
        // 这里暂时只更新订单状态，后续可以根据需要扩展
        int result = orderMapper.updateStatus(orderNo, order.getStatus(), status);
        return result > 0;
    }

    /**
     * 生成订单号
     * 使用时间戳+随机数的方式
     *
     * @return 订单号
     */
    private String generateOrderNo() {
        // 生成格式：yyyyMMddHHmmss + 4位随机数
        String timeStr = String.format("%tY%<tm%<td%<tH%<tM%<tS", new Date());
        String randomStr = String.format("%04d", (int) (Math.random() * 10000));

        return timeStr + randomStr;
    }
}
